//
//  YSSearchBookWebVC.m
//  Pods-YSDownLoadManager_Example
//
//  Created by Kyson on 2018/11/27.
//

#import <WebKit/WebKit.h>
#import "YSSearchBookWebVC.h"
#import "NSURLProtocol+WKWebVIew.h"
#import "YSHybirdHelper.h"
#import "YSDownLoadManager.h"
#import "YSDownloadListernVC.h"
#import "NSString+YSDownloader.h"
#import "YSDownloadBookModel.h"
#import "YSSqliteModelTool.H"

/// 百度搜索txt
static NSString * const kBaiduTXTURL = @"https://m.baidu.com/s?wd=txt%E5%B0%8F%E8%AF%B4%E4%B8%8B%E8%BD%BD";

/// 奇书
static NSString * const kQishuURL = @"http://m.qishu.cc/";

/// 下书网
static NSString * const kXiashuURL = @"https://m.xiashu.la/";


@interface YSSearchBookWebVC () <WKNavigationDelegate, WKScriptMessageHandler, WKUIDelegate, UIAlertViewDelegate>

@property (nonatomic, weak) WKWebView *webView;
@property (nonatomic, weak) UIProgressView *progressView;

@property (nonatomic, copy) NSString *currentURL;

@property (nonatomic, copy) NSString *downloadURL;


@end

@implementation YSSearchBookWebVC

- (void)showDownloadVC {
    [self.navigationController pushViewController:[YSDownloadListernVC new] animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [[YSHybirdHelper sharedHelper] setHybird:self.currentURL];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[YSHybirdHelper sharedHelper] setHybird:@"estimatedProgress"];
}

- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    self.view.backgroundColor = [UIColor whiteColor];
    [NSURLProtocol wk_registerScheme:@"http"];
    [NSURLProtocol wk_registerScheme:@"https"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"下载" style:UIBarButtonItemStylePlain target:self action:@selector(showDownloadVC)];
    
    //进度条
    UIProgressView *progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.progressView = progressView;
    [self.progressView setTrackTintColor:[UIColor colorWithWhite:1.0f alpha:0.0f]];
    [self.progressView setFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height -self.progressView.frame.size.height, self.view.frame.size.width, self.progressView.frame.size.height)];
    [self.navigationController.navigationBar addSubview:self.progressView];
    
    // 底部操作按钮
    CGFloat bottomH = 40;
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - bottomH, [UIScreen mainScreen].bounds.size.width, bottomH)];
    bottomView.backgroundColor = [UIColor colorWithRed:250/255.0 green:250/255.0 blue:250/255.0 alpha:1];
    [self.view addSubview:bottomView];
    
    UIButton *goBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [goBackButton setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    [goBackButton setImage:[UIImage imageNamed:@"left_dis"] forState:UIControlStateDisabled];
    goBackButton.frame = CGRectMake(20, 0, bottomH, bottomH);
    [goBackButton addTarget:self action:@selector(goBackButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:goBackButton];
    
    UIButton *goForwordButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [goForwordButton setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
    [goBackButton setImage:[UIImage imageNamed:@"right_dis"] forState:UIControlStateDisabled];
    goForwordButton.frame = CGRectMake(70, 0, bottomH, bottomH);
    [goForwordButton addTarget:self action:@selector(goForwordButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:goForwordButton];
    
    UIButton *reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [reloadButton setImage:[UIImage imageNamed:@"reload"] forState:UIControlStateNormal];
    reloadButton.frame = CGRectMake(self.view.frame.size.width - 40 - 3*bottomH, 0, bottomH, bottomH);
    [reloadButton addTarget:self action:@selector(reloadButtonDidClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:reloadButton];
    
    UIButton *adButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [adButton setImage:[UIImage imageNamed:@"ad_sel"] forState:UIControlStateNormal];
    [adButton setImage:[UIImage imageNamed:@"ad_nor"] forState:UIControlStateSelected];
    adButton.frame = CGRectMake(self.view.frame.size.width - 30 - 2*bottomH, 0, bottomH, bottomH);
    [adButton addTarget:self action:@selector(adButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:adButton];
    
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [collectButton setImage:[UIImage imageNamed:@"star_nor"] forState:UIControlStateNormal];
    [collectButton setImage:[UIImage imageNamed:@"star_sel"] forState:UIControlStateSelected];
    collectButton.frame = CGRectMake(self.view.frame.size.width - 20 - bottomH, 0, bottomH, bottomH);
    [collectButton addTarget:self action:@selector(collectButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:collectButton];

    
    // webview
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [[WKUserContentController alloc] init];
    
    // 文档完成加载时
    NSString *docEndInjectionJS = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"DocEndInjection" withExtension:@"js"] encoding:NSUTF8StringEncoding error:NULL];
    // 在document加载完成后执行注入js脚本
    WKUserScript *docEndScript = [[WKUserScript alloc] initWithSource:docEndInjectionJS injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [configuration.userContentController addUserScript:docEndScript];
    
    [configuration.userContentController addScriptMessageHandler:self name:@"docEndInjection"];

    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - bottomH - 64) configuration:configuration];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    [webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    self.webView = webView;
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:kQishuURL]];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}

#pragma mark - Actions
- (void)goBackButtonDidClick {
    if (self.webView.canGoBack) {
        [self.webView goBack];
    }
}

- (void)goForwordButtonDidClick {
    if (self.webView.canGoForward) {
        [self.webView goForward];
    }
}

- (void)reloadButtonDidClick {
    [self.webView reload];
}

- (void)adButtonDidClick:(UIButton *)btn {
    btn.selected = !btn.isSelected;
    [[NSUserDefaults standardUserDefaults] setObject:btn.selected ? @"1" : @"0" forKey:@"AD"];
    
    if (btn.selected) {
        [[YSHybirdHelper sharedHelper] setHybird:@""];
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"docEndInjection"];
    } else {
        [[YSHybirdHelper sharedHelper] setHybird:self.currentURL];
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"docEndInjection"];
    }
    
    [self.webView reload];
}

- (void)collectButtonDidClick:(UIButton *)btn {
    btn.selected = !btn.isSelected;
}

- (void)setCurrentURL:(NSString *)currentURL {
    _currentURL = currentURL;
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"AD"] isEqualToString:@"0"]) {
        [[YSHybirdHelper sharedHelper] setHybird:currentURL];
    }
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        BOOL animated = self.webView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:(float) self.webView.estimatedProgress animated:animated];
        
        //加载完成隐藏进度条
        if (self.webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.progressView.hidden = YES;
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
                self.progressView.hidden = NO;
            }];
        }
    }
}

#pragma mark - WKNavigationDelegate
/// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSLog(@"是否允许加载? %@", navigationAction.request.URL.absoluteString);
        
    if ([navigationAction.request.URL.absoluteString hasSuffix:@".txt"] || [navigationAction.request.URL.absoluteString hasSuffix:@".zip"] || [navigationAction.request.URL.absoluteString hasSuffix:@".rar"]) {
        NSString *string = @"";
        if ([navigationAction.request.URL.absoluteString hasSuffix:@".txt"]) {
            string = @"TXT";
        } else if ([navigationAction.request.URL.absoluteString hasSuffix:@".zip"]) {
            string = @"ZIP";
        } else {
            string = @"RAR";
        }
        
        self.downloadURL = navigationAction.request.URL.absoluteString;
        
        // 检测到TXT下载请求，您确定要添加到下载任务列表么？
        NSString *message = [NSString stringWithFormat:@"检测到%@下载请求，您确定要添加到下载任务列表么？", string];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    NSArray *temp = [navigationAction.request.URL.host componentsSeparatedByString:@"."];
    if (temp.count >= 3) {
        self.currentURL = temp[1];
    }
    
    
//    if (![navigationAction.request.URL.absoluteString containsString:@"m.qishu.cc"]) {
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;
//    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

/// 在收到服务器的响应头，根据response相关信息，决定是否跳转。decisionHandler必须调用，来决定是否跳转，参数WKNavigationActionPolicyCancel取消跳转，WKNavigationActionPolicyAllow允许跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    NSLog(@"知道返回内容之后，是否允许加载，允许加载");
    
    
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}

/// 页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"开始加载");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

/// 接收到服务器跳转请求之后调用 (服务器端redirect)，不一定调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"跳转到其他的服务器");
}

/// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"网页由于某些原因加载失败, 失败原因:%@", [error description]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

/// 开始获取到网页内容时返回
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"网页开始接收网页内容");
}

/// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"网页导航加载完毕");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

/// 加载失败
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败,失败原因:%@", [error description]);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"网页加载内容进程终止");
}

// 处理页面的alert弹窗
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:webView.URL.host message:message preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Close", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark WKMessageHandle Implementation

//处理当接收到html页面脚本发来的消息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"注入 messgae：%@", message);
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex > 0) {
        
        YSDownloadBookModel *bookModel = [[YSDownloadBookModel alloc] init];
        NSString *totalName = self.downloadURL.lastPathComponent;
        NSString *bookName = [totalName componentsSeparatedByString:@"."].firstObject;
        bookName = [bookName stringByRemovingPercentEncoding];
        
        bookModel.bookID = [bookName md5];
        bookModel.bookTitle = bookName;
        bookModel.bookUrl = self.downloadURL;
        bookModel.isDownload = YES;
        
        // 下载
        [[YSDownLoadManager shareInstance] downLoadWithURL:[NSURL URLWithString:self.downloadURL] downLoadInfo:^(long long fileSize) {
            bookModel.totalSize = fileSize;
            [YSSqliteModelTool saveOrUpdateModel:bookModel uid:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadCache" object:nil];
        } progress:^(float progress) {
            bookModel.progress = progress;
            [YSSqliteModelTool saveOrUpdateModel:bookModel uid:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadCache" object:nil];
        } success:^(NSString *filePath) {
            bookModel.isDownload = NO;
            bookModel.bookPath = filePath;
            bookModel.progress = 1;
            [YSSqliteModelTool saveOrUpdateModel:bookModel uid:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadCache" object:nil];
        } failed:^{
            NSLog(@"下载失败");
        }];
    }
}

@end
